package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import util.IdWorker;

import java.util.Date;
import java.util.List;

@Service
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    //增加吐槽
    public void save(Spit spit) {
        spit.set_id(idWorker.nextId() + "");

        spit.setThumbup(0);//点赞
        spit.setVisits(0);//访问量
        spit.setState("1");//状态
        spit.setShare(0);//分享量
        spit.setPublishtime(new Date());//发布时间
        spit.setComment(0);//回复量

        if (!StringUtils.isEmpty(spit.getParentid())) {
            //该吐槽是其他吐槽的回复  =>  其他吐槽的回复量加1
            //根据Id查询
            Query query = new Query();
            //添加条件
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));

            //修改comment值为原有值+1(每update一次改值加一)
            Update update = new Update();
            update.inc("comment", 1);

            //用mongoTemplate来更新数据,Dao中没有提供该方法(要使用自定义的操作要使用mongoTemplate)
            mongoTemplate.updateFirst(query, update, "spit");
        }
        spitDao.save(spit);
    }

    //查询所有吐槽
    public List<Spit> findAll() {
        return spitDao.findAll();
    }

    //根据查询吐槽
    public Spit findById(String spitId) {
        return spitDao.findById(spitId).get();
    }

    //修改吐槽
    public void update(String spitId, Spit spit) {
        spit.set_id(spitId);
        spitDao.save(spit);
    }

    //删除吐槽
    public void delete(String spitId) {
        spitDao.deleteById(spitId);
    }

    //根据ParentId分页查询回复
    public Page<Spit> findByParentId(String parentid, Integer page, Integer size) {
        return spitDao.findByParentid(parentid, PageRequest.of(page - 1, size));
    }

    //点赞吐槽
    public void thumbup(String spitId) {
        //根据Id查询
        Query query = new Query();
        //添加条件
        query.addCriteria(Criteria.where("_id").is(spitId));

        //修改thumbup值为原有值+1(每update一次改值加一)
        Update update = new Update();
        update.inc("thumbup", 1);

        //用mongoTemplate来更新数据,Dao中没有提供该方法(要使用自定义的操作要使用mongoTemplate)
        mongoTemplate.updateFirst(query, update, "spit");
    }


}
